library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity pseudoTop is
	generic(W:integer:=37;
		  ABUS:integer:=18;  --BUS DE DIRECCION DE LA RAM
		  DBUS: integer:=16; --BUS DE DATOS DE LA RAM
                -- Default settings:
                -- 19200 baud, 8 data bits, 1 stop bit
              DBIT: integer:=8;               -- # data bits
              SB_TICK: integer:=16;   -- # ticks for stop bits. 16/24/32 
              DVSR: integer:= 163;    -- baud rate divisor
              DVSR_BIT: integer:=8   -- # bits of DVSR
		  );
end entity;

architecture arch of pseudoTop is
signal clk, reset: std_logic:='0';

signal tick, rx, rx_done_tick: std_logic;
signal rx_dout,tx_din: std_logic_vector(7 downto 0);
signal tx,tx_start, tx_done_tick, tx_start_bis: std_logic;

signal done_delayed: std_logic;

type data_file_t is file of character;
file datos: data_file_t open read_mode IS "./datos.txt";

begin

baud_gen_unit: entity work.mod_m_counter(arch)
	generic map(M=>DVSR, N=>DVSR_BIT)
	port map(clk => clk, reset => reset,
			q=> open, max_tick=> tick);

UART0_RX:entity work.uart_rx(arch)
	generic map(DBIT=>DBIT, SB_TICK=>SB_TICK)
	port map(clk=>clk, reset=>reset, s_tick => tick,
		rx=> rx, rx_done_tick => rx_done_tick,
		dout=> rx_dout);

UART0_TX:entity work.uart_tx(arch)
		generic map(DBIT=>DBIT, SB_TICK=>SB_TICK)
		port map(clk=>clk, reset=>reset,
			tx_start=>tx_start,
			s_tick=>tick, din=>tx_din,
			tx_done_tick=>tx_done_tick, tx=>tx);

---SIMULATION BEGIN
clk<=not clk after 10 ns;
tx_start<=done_delayed OR tx_start_bis;
tx_start_bis<='0' , '1' after 20 ns, '0' after 40 ns;
reset<='0', '1' after 10 ns, '0' after 20 ns;
rx<=tx;

test_sequence:process
	variable ch : character:='A';
begin
	while not (endfile(datos)) loop
	wait until clk='1' and clk'event ;
		if tx_done_tick='1' then
			READ(datos, ch);
			tx_din<=std_logic_vector(to_unsigned(character'pos(ch),8));
		end if;
	end loop;
	wait for 600 ns;
	file_close(datos);
	assert false report
		"End Simulation" severity failure;
	end process;

delayed: process(clk, reset)
		begin
		if reset = '1' then
		done_delayed<='0';
		elsif clk='1' and clk'event then
		done_delayed<=tx_done_tick;
		end if;
	end process;


watchdog:process
	begin
	wait for 10 ms;
	assert false report "timeout" severity failure;
	end process;
end arch;


